// PicView.cpp : implementation file
//

#include "stdafx.h"
#include "moretunes.h"
#include "PicView.h"
#include ".\picview.h"

#define COVER_POS(x, size) (size - x) / 2

// CPicView

IMPLEMENT_DYNAMIC(CPicView, CStatic)
CPicView::CPicView()
: _mode(0)
{
}

CPicView::~CPicView()
{
}


BEGIN_MESSAGE_MAP(CPicView, CStatic)
	ON_WM_PAINT()
END_MESSAGE_MAP()

// CPicView message handlers

#define SMALL_PIC_MAX 142
#define BIG_PIC_MAX 476
void CPicView::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	// Do not call CStatic::OnPaint() for painting messages
	if (!imgOriginal.IsNull()) {
		LPRECT r = new RECT();
		this->GetWindowRect(r);
		int width = imgOriginal.GetWidth();
		int height = imgOriginal.GetHeight();
		int maxSize = SMALL_PIC_MAX;
		if (_mode == 2)
			maxSize = BIG_PIC_MAX;
		::SetStretchBltMode(dc, HALFTONE);
		if (width >= maxSize || height >= maxSize) {
			if (width > height) {
				height = height * maxSize / width;
				width = maxSize;
			}
			else {
				width = width * maxSize / height;
				height = maxSize;
			}
		}
		imgOriginal.StretchBlt(dc,
			COVER_POS(width, r->right - r->left), COVER_POS(height, r->bottom - r->top),
			width, height);
		delete r;
	}
}

bool CPicView::loadPic(CString filename, int mode)
{
	_mode = mode;
	char buffer [MAX_PATH];
	memset (buffer, 0, sizeof(buffer));
	VERIFY(::GetModuleFileName(AfxGetInstanceHandle(), buffer, _MAX_PATH));
	CString sPath = (CString)buffer;
	sPath = sPath.Left(sPath.ReverseFind('\\'));
	sPath += "\\";
	filename = sPath + filename;

	if (!imgOriginal.IsNull())
		imgOriginal.Destroy();

	CFile fp;
	if (fp.Open(filename, CFile::modeRead)) {
		fp.Close();
		HRESULT hresult = imgOriginal.Load(filename);
		if (FAILED(hresult))
			return false;
	}
	else 
		imgOriginal.LoadFromResource(AfxGetInstanceHandle(),IDB_PIC_ALIEN_SMALL);

	// Redraw
	Invalidate();
	UpdateWindow();
	return true;
}
